import os
from util import Util
from openpyxl import load_workbook
from write.AbstractWrite import AbstractWrite


class CargoBenefitCalculation(AbstractWrite):
	def __init__(self):
		super().__init__()

	def setDic(self, cargoTextDic, cargoUnderlineDic, shipTextDic, shipUnderlineDic):
		self.cargoTextDic = cargoTextDic
		self.cargoUnderlineDic = cargoUnderlineDic
		self.shipTextDic = shipTextDic
		self.shipUnderlineDic = shipUnderlineDic

	def write(self):
		oldPath, newPath = self._getPath("效益测算表")
		workbook = load_workbook(filename=oldPath)
		# 获取sheet
		sheet = workbook["测算表"]

		# 修改拟用船舶
		sheet["D6"] = self._getCalculationShip(self.cargoUnderlineDic["货量"][0])

		# 修改运价
		if "基本运价" in self.cargoUnderlineDic.keys():
			sheet["D10"] = self.cargoUnderlineDic["基本运价"][0]

		# 修改客户名称
		# sheet["D4"] =  self.cargoTextDic["甲方"]
		Util.tryWrite2Excel(sheet, "D4", self.cargoTextDic, "甲方")
		# 修改货量
		# sheet["D9"] = self.cargoUnderlineDic["货量"][0]
		Util.tryWrite2Excel(sheet, "D9", self.cargoUnderlineDic, "货量")
		# 修改装港
		# sheet["D12"] = self.cargoUnderlineDic["装货港"][0]
		Util.tryWrite2Excel(sheet, "D12", self.cargoUnderlineDic, "装货港")
		# 修改卸货港
		# sheet["D11"] = self.cargoUnderlineDic["卸货港"][0]
		# sheet["D13"] = self.cargoUnderlineDic["卸货港"][0]
		Util.tryWrite2Excel(sheet, "D11", self.cargoUnderlineDic, "卸货港")
		Util.tryWrite2Excel(sheet, "D13", self.cargoUnderlineDic, "卸货港")

		# 修改装卸时间
		# sheet["D16"] = self.cargoUnderlineDic["允许装卸时间"][0]
		Util.tryWrite2Excel(sheet, "D16", self.cargoUnderlineDic, "允许装卸时间")

		workbook.save(newPath)

	def _getPath(self, modelName):
		oldName = ""
		outputPath = os.path.join(self.outputDir,
		                          "{shipName}V{voyage}".format(shipName=self.shipUnderlineDic["航次"][0],
		                                                       voyage=self.shipUnderlineDic["航次"][1]))
		if not os.path.exists(outputPath):
			os.makedirs(outputPath)
		files = os.listdir(self.modelPath)
		files.sort()

		for file in files:
			if os.path.splitext(file)[0] == modelName:
				oldName = file
		newname = "货附件3：{shipName}V{voyage}{oldname}".format(shipName=self.shipUnderlineDic["航次"][0],
		                                                        voyage=self.shipUnderlineDic["航次"][1],
		                                                        oldname=oldName)
		newPath = os.path.join(outputPath, newname)
		oldPath = os.path.join(self.modelPath, oldName)

		return oldPath, newPath

	def _getCalculationShip(self, ton):
		ton = int(ton)
		if ton < 30000:
			return "大振奋"
		elif 30000 <= ton < 50000:
			return "内贸宝字号"
		elif 50000 <= ton < 60000:
			return "安字号"
		else:
			return "新峰字号"
